package com.net.okhttphelper.download;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.net.okhttphelper.http.CommonCallBack;
import com.net.okhttphelper.http.DataCallBack;
import com.net.okhttphelper.http.ExceptionHandle;
import com.net.okhttphelper.utils.FileNameUtil;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.Okio;
import okio.Sink;
import okio.Source;

/**
 * 文件下载回调处理
 * @author jie
 */
public class CommonDownloadCallBack extends CommonCallBack {

    /**
     * 下载文件保存到本地的文件夹地址
     */
    private final String saveDirPath;

    public CommonDownloadCallBack(String saveDirPath, DataCallBack dataCallBack) {
        super(dataCallBack);
        this.saveDirPath = saveDirPath;
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) {
        if (mDataCallBack != null){
            BufferedSink mBufferedSink = null;
            try{
                // 获取文件服务器下载地址
                String url = call.request().url().toString();
                // 从服务器地址中获取到文件名
                String fileName = FileNameUtil.getFileNameByPath(url);
                // 创建一个本地文件
                File file = new File(saveDirPath, fileName);
                // 判断是否存在同名文件
                if (FileUtils.isFileExists(file)){
                    // 若存在同名文件，则删除它
                    boolean delete = FileUtils.delete(file);
                    LogUtils.i("删除同名文件: " + delete);
                }
                // 将服务器数据写入到本地文件中
                Sink sink = Okio.sink(file);
                mBufferedSink = Okio.buffer(sink);
                ResponseBody responseBody = response.body();
                Source source = responseBody.source();
                mBufferedSink.writeAll(source);
                mBufferedSink.flush();
                // 下载完成，返回文件的本地路径
                mDataCallBack.success(file.getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
                ExceptionHandle.handleException(e.getCause(), mDataCallBack);
            } finally {
                if (mBufferedSink != null){
                    try {
                        mBufferedSink.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
